package boxync;

import java.io.File;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OptionalDataException;
import java.net.Socket;
import java.util.ArrayList;
import org.apache.commons.io.FileUtils;

public class Client {
    /**
     * Jumlah detik default untuk bertukar update dengan Server
     */
    public static final int DEFAULT_INTERVAL = 3;
    
    public static final String DELETED_LOG_FILENAME = "__deleted.txt";
    
    /**
     * Interval pengecekan update ke/dari server
     */
    public int updateInterval;
    
    /**
     * Socket untuk komunikasi dengan server
     */
    public Socket clientSocket;
    public ObjectOutputStream clientOut;
    public ObjectInputStream clientIn;
    
    /**
     * Direktori kerja Client
     */
    public BoxyncDir work;
    
    /**
     * True jika Client telah login
     */
    public boolean connected;
    
    /**
     * Thread yg mensync Client dengan Server
     */
    public ClientThread thread;
    
    public Client() {
        updateInterval = DEFAULT_INTERVAL;
        connected = false;
        thread = null;
        work = null;
    }
    
    /**
     * Mengubah direktori kerja client menjadi _path
     * @param _path direktori kerja baru client
     */
    public void setDir(String _path) {
        if (work == null) {
            work = new BoxyncDir(null, _path + "/Boxync");
            FileHelper.readDeletedLog(work);
            (thread = new ClientThread(work)).start();
        } else {
            String old = work.file;
            work.move(_path);
            work = new BoxyncDir(null, _path);
            FileHelper.readDeletedLog(work);
            
            thread.stopped = true;
            try {
                Thread.sleep(updateInterval*1000);
            } catch (InterruptedException e) {
                System.err.println("InterruptedExc in Client.setDir()");
            }
            
            try {
                FileUtils.deleteDirectory(new File(old));
            } catch (IOException e) {
                e.printStackTrace();
            }
            (thread = new ClientThread(work)).start();
        }
    }
    
    /**
     * Handler login, sekaligus membuat dan menstart thread yg akan mensync dengan Server
     * @param username
     * @param password
     * @return true jika login berhasil
     */
    public boolean handleLogin(String username, String password) {
        if (work == null)
            return false;
        
        try {
            clientSocket = new Socket(Server.IP_ADDRESS, Server.PORT);
            clientOut = new ObjectOutputStream(clientSocket.getOutputStream());
            clientIn = new ObjectInputStream(clientSocket.getInputStream());
        } catch (IOException e) {
            System.err.println("IOExc in Client.Client()");
        }
        String workdir = login(username, password);
        if (!workdir.equals("")) {
            connected = true;
            
            thread.socket = clientSocket;
            thread.in = clientIn;
            thread.out = clientOut;
            
            return true;
        }
        
        return false;
    }
    
    /**
     * 
     * @param username
     * @param password
     * @return String direktori jika login berhasil, String kosong jika gagal
     */
    public String login(String username, String password) {
        writeToServer(BoxyncProtocol.LOGIN_REQUEST);
        
        BoxyncSecurity sec = new BoxyncSecurity();
        writeToServer(sec.encrypt(username));
        writeToServer(sec.encrypt(password));
        
        String result = null;
        result = readFromServer();
        if (result.equals(BoxyncProtocol.LOGIN_ACCEPT)) {
            result = readFromServer();
        } else if (result.equals(BoxyncProtocol.LOGIN_DENY)) {
            result = "";
        }
        
        return result;
    }
    
    /**
     * Shutdown Client, send message logout dan close semua resource
     */
    
    public void handleLogout() {
        try {
            clientOut.writeObject(BoxyncProtocol.LOGOUT);
            clientOut.flush();
            clientIn.close();
            clientOut.close();
        } catch (IOException e) {
            System.err.println("IOExc in Client.stop()");
        }    
    }
    
    /**
     * Menulis semua deleted file ke log saat user tidak login dan user menutup aplikasi Client
     */
    public void handleClose() {
        if (!connected)
            FileHelper.writeDeletedLog(work);
    }
    
    /**
     * Mengembalikan hasil pembacaan String dari server sebanyak satu baris dan mencetak ke System.out
     * @return satu baris String hasil pembacaan
     */
    public String readFromServer() {
        String result = null;
        try {
            result = (String)clientIn.readObject();
        } catch (IOException e) {
            System.err.println("IOExc in Server.readFromSocket()");
        } catch (ClassNotFoundException e) {
            System.out.println(e);
        }
        System.out.println("Read from server: " + result);
        
        return result;
    }
    
    /**
     * Menulis String str ke server dan mencetak str ke System.out
     * @param str String yg ingin ditulis
     */
    public void writeToServer(String str) {
        System.out.println("Write to server: " + str);
        try {
            clientOut.writeObject(str);
            clientOut.flush();
        } catch (IOException e) {
            System.err.println("IOExc in Client.writeToServer()");
        }
    }
    
    public static void main(String[] args) {
        Client c = new Client();
        c.setDir("D:/src");
        c.handleLogin("wibi", "wibi");
    }
    
    /**
     * Thread untuk bertukar update dengan Server
     */
    class ClientThread extends BoxyncThread {
        public ClientThread(BoxyncDir _dir) {
            super(_dir);
            socket = clientSocket;
            in = clientIn;
            out = clientOut;
        }
        
        @Override
        public void run() {
            while (!stopped) {
                try {
                    Thread.sleep(updateInterval*1000);
                    if (connected) {
                        exchangeUpdates();
                    } else {
                        syncWithExplorer();
                    }
                    System.out.println("");
                } catch (InterruptedException e) {
                    System.err.println("InterruptedExc in ClientThread.run()");
                } catch (BoxyncException e) {
                    System.err.println(e);
                }
            }
        }
        
        /**
         * Bertukar update dengan Server, dimulai dengan Client mendorong update
         * baru kemudian Server mendorong update
         */
        @Override
        public void exchangeUpdates() throws BoxyncException {
            syncWithExplorer();
            pushUpdates();
            
            ArrayList<String> updates = pullUpdates();
            for (String update : updates) {
                handleUpdate(update);
            }
        }
        
        @Override
        public void handleUpdate(String update) {
            FileInfo fi = dir.searchFile(FileInfo.getFileName(update));
            try {
                if (fi != null) {
                    if (BoxyncFile.isDeleted(update)) {
                        System.out.println("DELETING FILE");
                        fi.delete();
                    } else {
                        System.out.println("REQUESTING FILE DOWNLOAD");
                        requestDownload(update);
                    }
                } else {
                    if (BoxyncFile.isDeleted(update)) {
                        // do nothing
                    } else {
                        System.out.println("REQUESTING FILE DOWNLOAD");
                        requestDownload(update);
                    }
                }
            } catch (BoxyncException e) {
                System.err.println(e);
            }
        }
        
        /**
         * Mengembalikan hasil pembacaan in sebanyak satu baris dari Client dan mencetak ke System.out
         * @return satu baris String hasil pembacaan
         */
        @Override
        public String read() {
            String result = null;
            boolean loop;
            do {
                loop = false;
                try {
                    result = (String)in.readObject();
                    System.out.println("Read from " + socket.getPort() + ": " + result);
                    if (result.equals(BoxyncProtocol.REQUEST_UPDATE)) {
                        handleDownload();
                        loop = true;
                    }
                } catch (IOException e) {
                    System.err.println(e);
                } catch (BoxyncException e) {
                    System.err.println(e);
                } catch (ClassNotFoundException e) {
                    System.err.println(e);
                } catch (Exception e) {
                    System.err.println(e);
                }
            } while (loop == true);
            
            return result;
        }
        
        /**
         * Mengembalikan hasil pembacaan in sebanyak satu baris dari Client tanpa mencetak ke System.out
         * @return satu baris String hasil pembacaan
         */
        @Override
        public String readWOPrint() {
            String result = null;
            boolean loop;
            do {
                loop = false;
                try {
                    result = (String)in.readObject();
                    if (result.equals(BoxyncProtocol.REQUEST_UPDATE)) {
                        handleDownload();
                        loop = true;
                    }
                } catch (IOException e) {
                    System.err.println(e);
                } catch (BoxyncException e) {
                    System.err.println(e);
                } catch (ClassNotFoundException e) {
                    System.err.println(e);
                } catch (Exception e) {
                    System.err.println(e);
                }
            } while (loop == true);
            
            return result;
        }
    }
}
